package org.ms.mtx.example.service;

import org.apache.commons.lang3.StringUtils;
import org.ms.mtx.core.annotation.Transactional;
import org.ms.mtx.core.exception.TransactionalException;
import org.ms.mtx.example.service.cannel.PayCancelService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 支付服务
 *
 * @author lry
 */
@Service
public class PayService {

    /**
     * 模拟余额
     */
    public static AtomicInteger money = new AtomicInteger(1000);

    @Resource
    private ScoreService scoreService;

    @Transactional(cancelClass = PayCancelService.class)
    public Boolean pay(Integer my, String exceptionMock) {
        if (StringUtils.isNotBlank(exceptionMock) && exceptionMock.equals(Thread.currentThread().getStackTrace()[1].getMethodName())) {
            throw new RuntimeException("模拟异常:" + Thread.currentThread().getStackTrace()[1].getMethodName());
        }

        if (money.get() - my <= 0) {
            throw new RuntimeException("余额不足");
        } else {
            System.out.println("校验余额:" + money.get());
        }

        return true;
    }

    public Boolean payConfirm(Integer my, String exceptionMock) {
        if (StringUtils.isNotBlank(exceptionMock) && exceptionMock.equals(Thread.currentThread().getStackTrace()[1].getMethodName())) {
            throw new RuntimeException("模拟异常:" + Thread.currentThread().getStackTrace()[1].getMethodName());
        }

        // 模拟支付扣款
        System.out.println("扣减余额:余额从[" + money.get() + "]减少为[" + money.addAndGet(-my) + "]");

        // 增加积分
        Boolean flag;
        try {
            flag = scoreService.addScore(my, exceptionMock);
        } catch (Exception e) {
            throw new TransactionalException("增加积分异常", e);
        }
        if (flag == null || !flag) {
            throw new TransactionalException("增加积分失败");
        }

        return true;
    }


}
